javascript - 异步执行函数的返回值

标签 javascript asynchronous es6-promise

我有一个调用子函数的父函数。

子函数将异步执行其内部代码,因此我希望父函数调用子函数,然后继续执行而无需等待。

function childFunc() {

  axios.post("http://api.example.com/user", { foo: "bar } ).
    then((response) => {

      // Do stuff here

      console.log("SUCCESS");
      return [1, 2, 3];

    }).
    catch((err) => {

      // Do stuff here

      console.log("ERROR");
      return [];

    });

  console.log("About to return null");

}

function parentFunc(url, data) { 

  // Call childFunc but then continue execution

  new Promise(function(resolve, reject) {

    let result = childFunc(url, data);
    result.length > 0 ? resolve(result) : reject("some error");

  });

  console.log("Continuing execution of `parentFunc()`");

  // Continue doing other stuff

}

我刚刚了解 Promiseasync JavaScript 中的行为,所以我对以下内容感到困惑:

  1. 什么会childFunc返回?如果axios.post异步执行,执行是否总是继续过去并返回 null ?请问return里面的语句then()catch()曾经火过吗?它会返回两次吗?

  2. parentFunc中的逻辑是这样吗?做我期望它在这里做的事情:调用 childFunc异步地同时推进自己的执行?我见过async/await语法,但不确定它是如何真正工作的以及是否可以以某种方式在这里使用。

谢谢!

最佳答案

What will childFunc return? If axios.post is executed asynchronously, wont the execution always continue past that and return null? Will the return statements inside then() or catch() ever fire? Does it return something twice?

childFunc 现在不返回任何内容或 undefined,因为您没有从中返回任何内容。

Will the logic in parentFunc do what I expect it to do here: call childFunc asynchronously while simultaneously moving forward with its own execution? I've seen the async/await syntax, but wasn't sure how that really worked and whether that could be used here somehow.

有点..您不需要显式使用 Promiseaxios 已经使用了 JS Promise API 并公开了您可以传递的 Promise 对象。

实际上,您的代码理想情况下应如下所示:

function childFunc() {

    return axios.post("http://api.example.com/user", { // childFunc now returns a Promise<Array<Number>>
        foo: "bar" } ).
      then((response) => {

            // Do stuff here

            console.log("SUCCESS");
            return [1, 2, 3];

        }).
        catch((err) => {

            // Do stuff here

            console.log("ERROR");
            return [];

        });

    // console.log("About to return null"); really would've been undefined, not null

}

function parentFunc(url, data) {

    // Call childFunc but then continue execution

    childFunc().then(results => {
        console.log("These are the results of the child function", results)
    // if you wanted to wait for childFunc to finish before continuing execution, put the statements to be executed after the childFunc execution here
    }).catch(err => {
        console.error("There was some error executing 'childFunc': " + err);
    })


    console.log("Continuing execution of `parentFunc()`");

    // Continue doing other stuff

}

编辑:

添加了滚动您自己的/创建我们自己的 Promise 的示例:

function longRunningCall() {
    return new Promise(function (resolve, reject) {
        try {

            setTimeout(function () {
                console.log("Done");
                resolve("done");
            }, 3000);
        } catch (error) { // this will never happen, but just to demonstrate handling errors asynchronously
            reject("error");
        }
    });
}

longRunningCall().then(function(result) {
    // the value of result will be "done";
}).catch(function(err) {
    // if there was an error, the value of err would be "error"
})

关于javascript - 异步执行函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58806162/

相关文章:

javascript - 在 jquery 对话框中插入表单

javascript - 谷歌地图 : Embedded code for "directions to" an office?

javascript - Web scraper 使用 Rx.js 遍历页面

javascript - Promise.all() 使用 Backbone 解决 IE 11

javascript - Math.random 和 splice 随机删除数组元素

javascript - MySQL关闭后Node.js进程无法恢复,再开启

Javascript Promise 和异步代码

javascript - Angular 2 : Binding Data using Elasticsearch Client

javascript - typescript 检查 promise 正文是否未调用 `resolve`

javascript - 获取在 Promise.race 中完成了哪个 promise