简体   繁体   中英

Get the return value of a single function within Promise

I have the following snippet containing a Promise:

...
return Promise.all([postHTTP()])
 .then(function (results) {
   loginToken = results[0].data.token;
   console.log("token:" + loginToken);
   })
   .catch(error => {
   throw error;
});
...

And the function:

function postHTTP() {
    request.post({
        headers: { 'content-type': 'application/json' },
        url: 'http://localhost:55934/api/Token',
        body: { "email": "test@test.pt", "password": "test" },
        json: true
    }, function (error, response, body) {
        if (error) {
            throw error;
        }
        console.log("return test");
        return body.token;
    });

Altough the String "Return test" is printed, it gives me an error in the Promised above saying the following:

(node:15120) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'token' of undefined

Can anyone help me finding a solution or the problem source for this?

Thanks in advance, Diogo Santos

The problem in your postHTTP function. When work with multi promise you have to pass array of promises into Promise.all , hence you function must look like this:

function postHTTP() {
  return new Promise(function (resolve, reject) {
    request.post({
        headers: { 'content-type': 'application/json' },
        url: 'http://localhost:55934/api/Token',
        body: { "email": "test@test.pt", "password": "test" },
        json: true
    }, function (error, response, body) {
        if (error) {
            return reject(error);
        }
        console.log("return test");
        return resolve(body.token);
    });
  });
}

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