来自早期承诺的控制台日志出现在来自最新承诺的控制台日志之后

时间:2020-07-25 19:11:55

标签: javascript promise sequence console.log

以下不是我的确切代码,但我只是想概述一下结构。当我运行代码时,我得到控制台日志的顺序是这样的:

  1. “完成”
  2. json

我期望这是相反的,因为要使function2完成(并发送“ Done”解析值),function3必须先完成。

我想了解为什么它不能那样工作。

function1().then(() => {
      return function2()
    ).then((message) => {
      console.log(message)
    })

    function function2() {
      return new Promise((resolve, reject) => {
        fetch(url, {
            method: 'get',
            body: null,
            headers: {
              "Content-Type": "application/json; charset=UTF-8",
              "Accept": "application/json; charset=UTF-8",

            },
          })
          .then(res => res.json())
          .then((json) => {
            return function3(json)
          })

        resolve('Done')
      })
    }

    function function3(json) {
      console.log(json)
    }

3 个答案:

答案 0 :(得分:4)

您甚至在resolve完成之前就致电fetch

如果将其移至另一个then,它将起作用:

// ...
.then(res => res.json())
.then((json) => {
    return function3(json)
})
.then(() => {
    resolve('Done')
})

但是实际上,整个new Promise甚至都没有必要,因为fetch已经返回了承诺!

// ...

function function2() {
    return fetch(url, { // It's important to actually *return* the promise here!
        method: 'get',
        body: null,
        headers: {
            "Content-Type": "application/json; charset=UTF-8",
            "Accept": "application/json; charset=UTF-8"
        }
    })
    .then(res => res.json())
    .then((json) => {
        return function3(json)
    })
    .then(() => {
        return 'Done'
    })
}

可以使用async / await进一步简化:

// I moved this into a function because the global module-level code
// is not in an async context and hence can't use `await`.
async function main () {
  await function1()
  console.log(await function2())
}

async function function1 () {
  // I don't know what this does, you didn't include it in your code snippet
}

async function function2 () {
  const response = await fetch(url, {
    method: 'get',
    body: null,
    headers: {
      "Accept": "application/json; charset=UTF-8"
    }
  })
  
  const json = await response.json()
  await function3(json)

  return 'Done'
}

// At the moment this wouldn't have to be async because you don't do anything
// asynchronous inside, but you had `return function3(json)` in the original code,
// so I assume it is *going* to be async later.
async function function3 (json) {
  console.log(json)
}

// Don't forget to .catch any rejections here! Unhandled rejections are a pain!
main().catch(console.error)

(在我这样做的时候,我删除了Content-Type标头,因为它对于GET请求毫无意义。)

答案 1 :(得分:1)

您已经错过了这样一个事实,即提取异步工作,并被加载到回调队列中,而这里的解析则以同步方式工作。因此,即使在解析之前完成提取操作,由于javascript循环,它仍会在解析后执行。您需要在进一步的获取链中进行链式解析,以实现所需的功能。

答案 2 :(得分:-2)

在函数2中,将调用fetch,并且仅暂停.then()链。下一个要读取的javascript是resolve(),它可以解决Promise。几秒钟后,promise解析并沿着链条继续到功能3,其中记录了“完成”