简体   繁体   中英

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. 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. What should be the proper way to do this?

resolve and reject are undefined in your function because they are out of scope. You should instead return a Promise from your init function, like so:

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. You should resolve when what you're trying to do is successful , and reject when what you're trying to do has failed. 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). Additionally, you should look into async & await which makes asynchronous code read more synchronously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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