function will return null from javascript post/get

New to JavaScript, and just started to read about Callback and Promise. I just don't understand the concept of "wait" until I have a value from a POST/GET request.

More specific, why won't this work?

var token = null;

/
/ var options = {headers, form, etc}
/

function getToken() {

    request(options)
        .then(function (parsedBody) {
            this.token = parsedBody
        })
        .catch(function (err) {
                console.log('POST-Error')
    })

    return token
}

console.log(getToken())

I'm using the 'request-promise' lib in nodejs. As I understand when request is called, then the token variable will be set since its a promise, right?


It's complicated and I don't blame you that you are confused. Everyone new to Node seems to get confused with that.

Your problem here is that the variable will be changed correctly - just not yet when the console.log() is run.

When a function returns a promise then it means that something will happen in the future - possibly in an instant, maybe later, but not yet at the time when that function returns the promise.

Then you can add a fulfillment and rejection handlers to the promise - those handlers will get called when the promise is actually resolved (ie there is some data returned by the request, or there is an error).

So, you cannot write:

console.log(getToken());

What you can write is:

getToken()
    .then(data => console.log('Data:', data))
    .catch(error => console.log('Error:', error));

But only when you actually return the promise from your function:

function getToken() {
    let promise = request(options);
    return promise;
}

Now, you could use an async keyword and do something like this:

async function getToken() {
    let data = await request(options);
    return data;
}

but this function doesn't return data - it returns a promise just like the previous example.

Remember one thing that you cannot return any value from your function that is not available yet. You can only return a promise if you want to return something before you have it. And every asynchronous function - whether it's async function , a function that explicitly returns a promise or a function that takes a callback - will return before the asynchronous action is done, without blocking the thread.

For more details see some of those answers:

  • A detailed explanation on how to use callbacks and promises
  • Explanation on how to use promises in complex request handlers
  • An explanation of what a promise really is, on the example of AJAX requests
  • An explanation of callbacks, promises and how to access data returned asynchronously
  • 链接地址: http://www.djcxy.com/p/55368.html

    上一篇: 然后在里面使用cancel()

    下一篇: 函数将从javascript post / get返回null