3 回答
TA贡献1817条经验 获得超6个赞
错误不是指myfunction而是start。
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function
const myfunction = async function(x, y) {
return [
x,
y,
];
}
// Start function
const start = async function(a, b) {
const result = await myfunction('test', 'test');
console.log(result);
}
// Call start
start();
我利用这个问题的机会来告诉你一个已知的反模式的使用await方法:return await。
错误
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
async function start() {
// useless await here
return await myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
正确
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
async function start() {
return myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
TA贡献1799条经验 获得超9个赞
当我收到此错误时,事实证明我在“异步”函数中调用了map函数,因此此错误消息实际上是指未标记为“异步”的map函数。通过从map函数中取消“ await”调用并提出了一些其他实现预期行为的方法,我解决了这个问题。
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}
TA贡献1830条经验 获得超9个赞
真正的问题是您需要了解异步/等待如何在这里工作。错误在于start function()
您需要定义功能Async函数的使用await作为
await 使用承诺/未来/任务返回方法/功能
async 将方法/功能标记为能够使用等待。
Await实际上是在执行promise / resolve的相同过程,并且由于该功能是async其他任务,因此正在并行处理
有关更多信息,请参考 MDN DOCS
async function foo(){
let myAsyncCall = await .... ('/endpoint') // hitting on some api
console.log(myAsyncCall) // myAsyncCall will log out whenever the request get resolved
}
foo()
添加回答
举报