JS - 在函数之后执行代码之前等待函数内的承诺完成 - 可能吗?

JS - Waiting for promise within function to finish before executing code after function -- possible?

我希望我的标题和简单的代码能够解释我想要做什么。我正在尝试调用 myFunction(),然后让这些承诺通过 Promise.all... 解决,然后在 myfunction();

之后执行代码
myfunction() {
  let x = promiseOneFunction();
  let y =  promiseTwoFunction();


 Promise.all([x, y]).then(values => {
            let valOne = = values[0];
            let valTwo = values[1];

            returnObj = {
                fistVal: valOne,
                destination: valTwo
            }

            console.log("return object within promise is ", returnObj);

            return returnObj;
        });

} // end myfunction

myfunction();
console.log("want to have this log after my function is finished");

谢谢!

当承诺完成时 运行 编码的唯一(明智)方法是:

  • 调用 then() 承诺
  • await 诺言

这意味着您需要承诺在 myfunction 之外可用。目前该功能 returns 没有。更改它,使其 returns Promise.all([x, y]).then(...) 返回的承诺(您目前忽略)。

return Promise.all([x, y]).then(...)

那么该 promise 将在函数外可用:

const the_promise = myfunction();

你可以在上面调用 then

the_promise.then(() => {
    console.log("want to have this log after my function is finished");
});

由于JS是单线程的,所有的异步函数都会被放到事件队列中,在主线程处理完当前function/block的代码后运行。

如果您希望某些事情严格在异步函数之后发生,您需要将其放在链接到异步函数的 .then() 块中,或者您可以使用新的 async/await 语法。一样的。

用 .then()

myAsyncFunc().then(result => {
 console.log(result)
})

使用 async/await,您首先将函数声明为异步函数

const myAsyncFunc = async () => {
 //Content of your function such as Promise.all
 //Returns a Promise
}

然后你这样称呼它:

const result = await myAsyncFunc();
console.log(result)