【问题标题】:Async Await Promises Typescript Gets Undefined [duplicate]异步等待承诺打字稿未定义[重复]
【发布时间】:2022-01-22 17:02:44
【问题描述】:

所以我有这样的功能

/** @ts-ignore eslint-disable */
declare var require: any
import generateString from "./Strings/GenerateString";
var txtomp3 = require("text-to-mp3");
const fs = require("fs");

export default async function newCaptcha(length: any) {
    let captcha = generateString();
    let binary: AudioBuffer;
    let err;
    txtomp3.getMp3(captcha, async(err: any, binaryStream: any) => {
        binary = binaryStream
    })
    return new Promise((resolve, reject) => {
        resolve(binary)
    })
}

我已经尝试记录 binaryStream 和验证码,但它们不是未定义的,而当我调用该函数时,

newCaptcha({ length: 1 }).then(binaryStream => {
    console.log(binaryStream)
}).catch(e => {
    console.error(e)
})

返回未定义

【问题讨论】:

  • 您将承诺返回给txtomp3.getMp3 的回调函数,而不是newCaptcha 函数。将其移出txtomp3.getMp3
  • 我试过了,对我没有帮助,还检查了一些,
  • 您需要将getMp3 函数调用包装在一个promise 中并返回该promise。然后在getMp3 回调中解决/拒绝。
  • 编辑了问题。所以基本上我现在正在解决 txttomp3 功能之外的承诺
  • 包装它似乎有效!谢谢你们!

标签: javascript typescript function async-await binary


【解决方案1】:

将 getMp3 包装在 Promise 中似乎可行

/** @ts-ignore eslint-disable */
declare var require: any
import generateString from "./Strings/GenerateString";
var txtomp3 = require("text-to-mp3");
const fs = require("fs");

export default async function newCaptcha(length: any) {
    let captcha = generateString();
    let binary: AudioBuffer;
    let err;
    return new Promise<AudioBuffer>((resolve, reject) => {
        txtomp3.getMp3(captcha, function(err: any, binaryStream: AudioBuffer) {
            resolve(binaryStream);
        })
    })
}



【讨论】:

  • 如果有错误,你也会想reject(err)
猜你喜欢
  • 1970-01-01
  • 2019-03-18
  • 2018-09-02
  • 1970-01-01
  • 1970-01-01
  • 2018-04-17
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多