async and await: When await processes the new Promise ((resolve, reject) =>{…}) object, the parameters of resolve() will be processed as the return value

The async keyword gives you an easier way to work with asynchronous Promise-based code. Add async to the beginning of a function to make it an asynchronous function.

async function myFunction() {
  // This is an asynchronous function
}

In an asynchronous function, you can use the await keyword before calling a function that returns a Promise. This causes the code to wait at that point until the Promise is fulfilled, at which point the response to the Promise is treated as a return value, or the rejected response is thrown as an error.

This enables you to write asynchronous functions like synchronous code. For example, we can use this to rewrite our fetch example.

async function fetchProducts() {
  try {
    // After this line, our function will wait for the `fetch()` call to complete
    // Calling `fetch()` will return a "response" or throw an error
    const response = await fetch(
      "https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
    );
    if (!response.ok) {
      throw new Error(`HTTP request error: ${response.status}`);
    }
    // After this line, our function will wait for the call to `response.json()` to complete
    // A call to `response.json()` will return a JSON object or throw an error
    const json = await response.json();
    console.log(json[0].name);
  } catch (error) {
    console.error(`Unable to get product list: ${error}`);
  }
}

fetchProducts();

Here we call await fetch(). What our caller gets is not a Promise, but a complete Response object, just like fetch() is the same as a synchronous function.

We can even use try...catch blocks to handle errors, just like when we write synchronous code.

But please note that this writing method only works in asynchronous functions. Async functions always return a Pomise, so you can’t do something like this:

async function fetchProducts() {
  try {
    const response = await fetch(
      "https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
    );
    if (!response.ok) {
      throw new Error(`HTTP request error: ${response.status}`);
    }
    const json = await response.json();
    return json;
  } catch (error) {
    console.error(`Unable to get product list: ${error}`);
  }
}

const json = fetchProducts();
console.log(json[0].name); // json is a Promise object, so this code will not work properly

Instead, you need to do something like:

async function fetchProducts() {
  try {
    const response = await fetch(
      "https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
    );
    if (!response.ok) {
      throw new Error(`HTTP request error: ${response.status}`);
    }
    const json = await response.json();
    return json;
  } catch (error) {
    console.error(`Unable to get product list: ${error}`);
  }
}

const jsonPromise = fetchProducts();
jsonPromise.then((json) => console.log(json[0].name));

You may use the async function wherever you need to use Promise chains, which also makes working with Promise more intuitive.

Remember, just like a Promise chain, await forces asynchronous operations to complete in series. This is necessary if the result of the next operation depends on the result of the previous operation, but if not, an operation like Promise.all() will have better performance.

Summary

Promises are the foundation of modern JavaScript asynchronous programming. They avoid deeply nested callbacks, make it easier to express and understand sequences of asynchronous operations, and they also support an error handling style similar to the try...catch statement in synchronous programming.

The async and await keywords make it easier to build an operation from a series of consecutive asynchronous function calls, avoid creating explicit Promise chains, and allow you to write like Write asynchronous code like synchronous code.

Promises work in the latest versions of all modern browsers; the only places where support issues arise is with Opera Mini and IE11 and earlier.

In this article, we have not covered all Promise features, only the most interesting and useful ones. As you start learning more about Promises, you’ll encounter more interesting features.

The first half is reproduced from:

https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Asynchronous/Promises

If you need to know the basic usage of promises, please refer to:

Using Promises – JavaScript | MDN

(The content of mozilla.org is very authoritative and detailed)

Before finding the above document, my understanding of promises came from Liao Xuefeng:

Promise – Liao Xuefeng’s official website

Due to lack of practical experience and not seeing the introduction of async/await later, I feel that Promise is very far away.

In fact, promise chain usage is not commonly used when making page requests. Promise + async/await is more often used to handle interface return values.

Here are common practical uses:

import store from "@/store"
function HTTP(obj, config) {

let defaultConfig = {
isRes: false,
loading: false
}

config = { ...defaultConfig,
...config
}


// If loading needs to be displayed, mask prevents click penetration
config.loading & amp; & amp; uni.showLoading({
title: 'Loading',
mask: true
});

return new Promise((resolve, reject) => {

let options = {
url: "",
method: "GET",
data: {},
dataType: "json",
header: {
"content-type": "application/json",
"X-requested-With": "XMLHttpRequest",
// Simulate user login
"X-Access-Token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2OTQ1MjM5NDEsInVzZXJuYW1lIjoiYWRtaW4ifQ.iGxw-j0uNi-rY96KuP9B4Jgx-t-Uk2mYZxVWMb7 ySbo"
},
success: (res) => {
console.log("HTTP request result:",res)
console.log("resolve:",resolve)
uni.hideLoading();
//The status code is 200
if (res.statusCode == 200) {
let data = res.data;

//Automatically verify whether the user's login has expired
if (data.code == "01") {
store.dispatch("reLogin");
return;
}

//Return { code:10000,msg:"Message",data:[] }
if (config.isRes) {
resolve(data)
}
//return data:[]
else {
if (data.code == "200") {
//console.log("data object:",data)
resolve(data.result||true)
} else {
wx.showToast({
title: data.message,
icon: "none",
duration: 2000
})
reject(data.message);
}
}
}else if(res.statusCode == 401) {
store.dispatch("reLogin");
return;
} else {
reject("HTTP: Status code exception!");
}
},
fail: (err) => {
uni.hideLoading();
uni.showToast({
title: "Network abnormality, please try again later!",
icon: "none",
})
reject("Network abnormality, please try again later!");
},
complete: () => {}
}

options = { ...options,
...obj
};
\t\t
const OPENID = uni.getStorageSync("openId");
const Token=uni.getStorageSync("token");
// const location=uni.getStorageSync("location");
// if(location){
// //All interfaces carry current location information
// options["data"]["latitude"] = location.latitude;
// options["data"]["longitude"] = location.longitude;
// options["data"]["pcitycode"] = location.pcitycode;
// }
console.log("Token===" + Token);
if (OPENID) options["header"]["openId"] = OPENID;
if (Token) options["header"]["X-Access-Token"] = Token;
if (options.url & amp; & amp; options.method) {
wx.request(options);
} else {
wx.showToast({
title: 'HTTP: Missing parameters',
icon: "none",
duration: 2000
})
}
})

}



export default {
GET(url, data = {}, config) {
return HTTP({
url,
data,
method: "GET"
}, config);
},
POST(url, data = {}, config) {
return HTTP({
url,
data,
method: "POST"
}, config);
},

POSTformdata(url, data = {}, config) {
return HTTP({
url,
data,
method: "POST"
}, config);
}
}

Remove the redundant parts of the code to facilitate explanation:

import store from "@/store"
function HTTP(obj, config) {
...
return new Promise((resolve, reject) => {
let options = {
url: "",
method: "GET",
data: {},
dataType: "json",
header: {...},
success: (res) => {... resolve(data.result||true); ...},
fail: (err) => {... reject("Network abnormality, please try again later!");},
complete: () => {}
}
options = { ...options, ...obj };
...
if (options.url & amp; & amp; options.method) {
wx.request(options);
}
...
})
}
export default {
GET(url, data = {}, config) {
return HTTP(...);
},
POST(url, data = {}, config) {
return HTTP(...);
},
POSTformdata(url, data = {}, config) {
return HTTP(...);
}
}

When POST() is finally called, the return value comes from return new Promise((resolve, reject) => {}), which is a promise object.

//From index.js, call the previously defined POST()
export const memberLogin = (data) => http.POST(`${config.baseUrl}/ums/memberLogin`, data);

//From loginPwd.vue, call memberLogin above
let response = await this.$apis.memberLogin(params);
console.log("response ",response );

When the final response was output, I found that the response was a json string, not a promise object. I was very surprised when I didn’t understand the role of await. It was even suspected that the assignment of response did not come from return new Promise((resolve, reject) => {}), but from wx.request(options). I want to set a breakpoint to observe the execution process of resolve(), but I can’t find the corresponding code.

After confirming let response = await this.$apis.memberLogin(params); the right side of the equal sign is the promise object and the left side is the ordinary object. It is speculated that the only answer comes from await. Maybe await processes the promise object and turns it into Ordinary objects.

I didn’t use Baidu to query the usage of await, and found the answer from mozilla.org.

Summarize:

When await is used with a Promise object, the parameters of resolve() in the Promise object will be used as the return value to replace the Promise object returned in the definition.

this.$apis.memberLogin(params) returns a promise object

await this.$apis.memberLogin(params) returns a normal object

Await promise object is equivalent to unpacking the promise object and only returns the parameters of resolve() in the promise object.

Baidu can only find advertisements, not real knowledge