简体   繁体   中英

Returning a string from within a promise chain that completes an API call

I have a function that completes a POST request and returns a string depending on the result of the API call. I'm strugglnig to return that string.

I know the below won't work as it just returns the unparsed JSON, but the API call completes.

return request('POST', url, { json: payload } )
        .then((res) => {
            let response = JSON.parse(res.getBody('utf8'));

            if(response['IsSuccess'] == true){
                return "Success String"
            }
            else if(response['Description']){
                return response['Description']
            }
            else{
                return BOOKING_ENGINE_FAILURE_MESSAGE;
            }

        })

How would I make this functional? I'm using then-request dependency in a Node 6 firebase environment.

Anything you return from inside a promise will be wrapped in a promise as well so you can continue the chain:

return request('POST', url, { json: payload } )
.then((res) => {
  let response = JSON.parse(res.getBody('utf8'));
  DialogflowHelper.logout_user(auth_token);
  if(response['IsSuccess'] == true){
    return "Success String"
  }
  else if(response['Description']){
    return response['Description']
  }
  else{
    return BOOKING_ENGINE_FAILURE_MESSAGE;
  }
})
.then( str => {
  // do something with the string we returned in the previous promise handler.
});

Or you could continue the chain from where you generate this response:

const create_request = ( url, payload ) => request('POST', url, { json: payload } )
.then((res) => {
  let response = JSON.parse(res.getBody('utf8'));
  DialogflowHelper.logout_user(auth_token);
  if(response['IsSuccess'] == true){
    return "Success String"
  }
  else if(response['Description']){
    return response['Description']
  }
  else{
    return BOOKING_ENGINE_FAILURE_MESSAGE;
  }
});

create_request().then( str => {
  // do something with the string we returned in the previous promise handler.
});

Once you start a promise chain, it's best to keep working with the chain. You could use the chain to update some outside variable, but that would also include doing checks on when you can start using that variable.

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