简体   繁体   English

在 JavaScript 中的承诺中返回早期解决的问题

[英]Trouble returning early resolve in promises in JavaScript

I have a function in which further execution is decided within the function itself.我有一个函数,其中在函数本身内决定了进一步的执行。 Need to use promises as it is an asynchronous function.需要使用 promises,因为它是一个异步函数。 The problem is that it continues execution even after resolve.问题是它即使在解决后仍继续执行。

My Code :我的代码:

function initApp () {
    token = getToken () ;
    if ( token == null ) {
        resolve ('Not Found') ;
    } else {
        // ... async process
        if ( tokenStatus == "true" ) {
            resolve ('Welcome') ;
        } else {
            resolve ('Invalid') ;
        }
    }
}

let init = new Promise ( ( resolve , reject ) => { 
    initApp ();
});

init.then((successMessage) => {
    alert ( successMessage ) ;
}

I am getting a undefined resolve error.我收到未定义的解析错误。 Also , earlier when I hadn't used else , it continued execution even after encountering resolve.此外,早些时候当我没有使用 else 时,即使遇到了 resolve,它也会继续执行。 What should be the proper way to do this?这样做的正确方法应该是什么?

resolve and reject are undefined in your function because they are out of scope. resolvereject在您的函数中未定义,因为它们超出了范围。 You should instead return a Promise from your init function, like so:你应该从你的 init 函数中返回一个 Promise,像这样:

function init () {
  return new Promise((resolve, reject) => {
    let token = getToken()
    if (!token) {
      reject('not found')
    } else {
      doSomethingAsync((tokenStatus) => {
        if (!tokenStatus) return reject('Invalid')
        resolve('Welcome')
      })
    }
  })
}

init().then((successMsg) => {
  alert(successMsg)
}).catch((errMsg) => {
  alert(errMsg)
})

You're also not using Promises correctly.您也没有正确使用 Promise。 You should resolve when what you're trying to do is successful , and reject when what you're trying to do has failed.当你尝试做的事情成功时你应该resolve当你尝试做的事情失败时你应该reject A takeaway for you my friend is to read up up on Promises as well as the basic parts of JavaScript (eg you're overwriting the init function with a variable later on).我的朋友给你的一个外卖是阅读 Promises 以及 JavaScript 的基本部分(例如,你稍后会用一个变量覆盖init函数)。 Additionally, you should look into async & await which makes asynchronous code read more synchronously.此外,您应该研究 async 和 await,它使异步代码的读取更加同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM