gpt4 book ai didi

javascript - 在执行其他操作之前等待方法任务完成

转载 作者:行者123 更新时间:2023-12-02 20:57:42 25 4
gpt4 key购买 nike

我有一个带有方法的类...其中一个实际上包含获取 svg 文件的 fetch 操作。那里没什么特别的。问题其实不在于类,而在于使用的时候。

我有一个方法 getDataFromFile(url),我将我的 SVG url 传递给它,它会执行很多操作。问题是...当我使用它时,如果我在它之后立即调用另一个方法,甚至只是一个 console.log...由于它尚未影响文件,我会在应该显示的位置出现“未定义”对象。

当然,如果我设置一个超时,它会起作用,但这意味着它之后的所有内容都必须处于超时状态...我也可以很好地在它之后调用的方法中设置一个超时,但是这个会也变得异步。

我尝试了很多事情,但我并没有真正得到 promise 之类的东西,所以......我完全被困在那里!

这是我的代码的(非常)简化版本,我知道它远非最佳(我是初学者),但无论如何它是:

var ParentClass = function ()
{
// Attributes and stuff

this.paths = [];
}


var MyClass = function ()
{
ParentClass.call( this );
}


MyClass.prototype.getInlineDOMdata = function ( selector )
{
// Stuff going on...

let querySelector = document.querySelectorAll( selector + " path" );

for ( let i = 0; i < querySelector.length; i++ )
{
this.paths.push(
{
name: querySelector[ i ].id,
color: querySelector[ i ].style.fill,
pathData: querySelector[ i ].attributes.d.value
}
);
}

}


MyClass.prototype.getInlineData = function ( inlineCode )
{
let domTarget = document.querySelector( "body" );

domTarget.innerHTML += `<div class="placeholder">${ inlineCode }<div>`;

let domContainer = document.querySelector( ".placeholder" );

// Stuff going on...

this.getInlineDOMdata( ".placeholder svg" );

domContainer.remove();
}


MyClass.prototype.getDataFromFile = function ( url )
{
fetch( url )
.then( response => response.text() )
.then( data => this.getInlineData( data ));
}

程序端看起来像这样:

document.addEventListener( "DOMContentLoaded", loadComplete );

function loadComplete ()
{
var test = new MyClass();
test.getInlineData( `
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 195 82">
<!--Some SVG code -->
</svg>
` );
console.log( test.paths[ 0 ] ); // Object { name... }
console.log( test.paths.length ); // 4


test.getInlineDOMdata( "svg" );
console.log( test.paths[ 0 ] ); // Object { name... }
console.log( test.paths.length ); // 4 */

test.getDataFromFile( "https://upload.wikimedia.org/wikipedia/en/c/ce/SVG-logo.svg" );
console.log( test.paths[ 0 ] ); // undefined
console.log( test.paths.length ); // 0

setTimeout( function ()
{
console.log( test.paths[ 0 ] ); // Object { name... }
console.log( test.paths.length ); // 4
}, 1000 );
}

所以当我使用 getInlineData 时,它起作用了。当我使用 getInlineDOMdata 时,它有效。当我使用 getDataFromFile 时,却没有!但如果我设置一个计时器,它就会起作用。

我发现这真的很“肮脏”,我迫切希望找到一种合适的解决方案,我可以直接在这个方法下面调用任何其他方法!

编辑:已解决!

使用async/await,只需将我的方法getDataFromFile更改为

MyClass.prototype.getDataFromFile = async function ( url )
{
let response = await fetch( url )
.then( response => response.text() );

await this.getInlineData( response );
}

和程序端,在我的 loadComplete 函数前面添加 async ,并在我的 test.getDataFromFile( 前面添加 await "urlToSvg.svg"); 行解决了我的问题!

感谢 Leftium 提供的很棒的教程( tutorial ),这让我终于明白了 Promise 是如何工作的

最佳答案

使用async/await 。这些关键字基本上是 Promise 的语法糖,因此了解 Promise 的工作原理将会非常有帮助。

这是一个很棒的tutorial使用 Promise 遍历异步示例,然后将其转换为 async/await 语法。相关引述:

The good news is that JavaScript allows you to write pseudo-synchronous code to describe asynchronous computation. An async function is a function that implicitly returns a promise and that can, in its body, await other promises in a way that looks synchronous.

...

Inside an async function, the word await can be put in front of an expression to wait for a promise to resolve and only then continue the execution of the function.

Such a function no longer, like a regular JavaScript function, runs from start to completion in one go. Instead, it can be frozen at any point that has an await, and can be resumed at a later time.

关于javascript - 在执行其他操作之前等待方法任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61432240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com