我正在使用访存Api从我的项目中读取本地文件。
一些代码也是如此,但是问题是我对请求的响应始终是先前的响应。
var tmplText = [sometextForReplament]
var textToBeReplace;
var enumText = [someText]//as example, here is where the $enum to be replaced is
async function ReadFileFromProject() {
let data = await fetch('/assets/groovy.txt')
.then(response => response.text())
.then(data => {
tmplText.push(data);
textToBeReplace = tmplText[0];
if (textToBeReplace.indexOf('$enum') > -1)
{
textToBeReplace = textToBeReplace.replace('$enum', enumText);
}
console.log(textToBeReplace);
console.log(filename + 'exported with success');
})
.catch(error => {
alert('Can not read local file:' + error);
return error;
});
}
我认为异步和等待是为了让我的异步请求不同步吗?
答案 0 :(得分:0)
我认为您确实需要研究方法的可重用性和程序流程,有些问题使没有完整的示例就很难猜测正在发生的事情,但是我建议重写一下指示您如何重构
function getData( url ) {
return fetch( url )
.then( response => {
if ( response.ok ) {
// return the response itself
return response;
}
// well the response wasn't okay, throw an error, break the chain
throw '400 Bad request';
});
}
function replaceContentWithEnumText( url, enumText ) {
return getData( url )
// valid data, we want the response as text
.then( resp => resp.text() )
// split the text (if any, and join it with enumText)
.then( text => {
return text && text.split( '$enum' ).join( enumText );
} );
}
// note for here it isn't a valid url, so you really wont see anything)
replaceContentWithEnumText( '/assets/groovy.txt', 'someText' )
// once in the below then, fetch has happened, your text was replaced, you can use replacedContent
.then( replacedContent => console.log( 'comleted succesfully, data returned would be ', replacedContent ) )
// something went wrong in the entire chain of events, handling it here makes sense
.catch( err => console.log( 'error occured', err ) );
如果我愿意通过您的原始代码,对我来说:
let data
分配给await fetch...
,数据最多将在其中包含错误消息,因为实际上只有从catch块中您才返回一些东西let data
变量没有任何作用data
参数(令人困惑)async/await
完全是多余的,您的代码甚至都没有使用它(我知道您相信await
使您的代码同步,但是,它不能像您想象的那样工作) async
标记的函数将隐式返回一个Promise。您可以await
承诺,然后将承诺链的响应返回给您分配的任何内容。您的代码将等待继续,直到承诺执行完毕(但不是您的程序,它将继续运行)。
它实际上只是诺言的句法糖,有人说它使它更具可读性,但这完全基于观点。