vue store中fetch/async/await怎么用?

722 阅读1分钟

首先,在mounted中要向store中发送一个action的请求,来修改store 中的type,但是由于后续要用到这个type值,导致在mounted中获取type时为空,无法解决,先解决办法如下,同时也明白了async和await的用法。

在store中用fetch发送请求:(修改之前)

[types.xxx]({commit, state: RootStateTypes}, param: any) {
  let newUrl = getUrl(`${xxx}`, param);  fetch(newUrl)     .then(res => res.json())     .then(res => {         commit(types.xxx, res.data);     console.log('data',res.data);   });
}

修改成:

async [types.xxx]({commit, state: RootStateTypes}, param: any) {        let newUrl = getUrl(`${xxx}`, param);        let response = await fetch(newUrl);        let data =  await response.json();        let d = data.data;        console.log('data',data);        return d;      },

在mounted中修改之前:

private mounted():void {                this.getX({trade: urlTrade});
}

修改成:

private async mounted():Promise<any> {    let x = await this.getX({trade: urlTrade});    console.log('xxxx',x);
}

关于上述改造过程,一直困扰的点是store返回的依旧是promise,而在mounted需要用then里面的res才能看到值,正当准备用此方法处理时,高人指点,这么做失去了async的意义,故在mouted里面加async和await解决,收获良多。

关于async和await的用法和思考:

被async包裹的函数,即使return 1,也会被包裹成promise。但是用await接收,会使async返回的promise恢复成原来的值。

async function test() {    return 'xxx';}async function t() {    let x = await test();    console.log('x',x)}t();

async内部await顺序执行

function getSomething() {    return 'something';}async function testAsync() {    return 'hello baidu';} async function test() {     const v = await getSomething();     const w = await testAsync();     console.log(v,w); }