简体   繁体   中英

Calling JavaScript functions. First function waits for the other which intern having the one more function for confirmation

I have two JavaScript function in two different files. On click I am calling first function to delete and second function for refresh the text in the div. The problem is delete function is having confirm action. So if I call one after the other refresh function is executing immediately. But I want refresh function to execute after confirmation (Note:delete and refresh JavaScript functions are there in two different projects)
Below is the sample:

function deleteIFAsset(a) {
    var id1 = a.id;
    IframeCloudEditor.deleteFileFromTimeline(id1);
    refreshAsseListt();
}

You'll have to use a callback. Any properly-designed library with asynchronous operations (like waiting for the user to confirm an action in an event-driven environment like a browser) should offer a callback for when that operation is complete. You haven't said what library the deleteFileFromTimeline comes from, but hopefully it offers a callback. The callback may be an argument you pass, or it may be part of a "promise" API.

If it accepts a callback directly, that would look something like this:

function deleteIFAsset(a) {
    var id1 = a.id;
    IframeCloudEditor.deleteFileFromTimeline(id1, function() {
        refreshAsseListt();
    });
}

or

function deleteIFAsset(a) {
    var id1 = a.id;
    IframeCloudEditor.deleteFileFromTimeline(id1, refreshAsseListt);
}

...if your refreshAsseListt (was that supposed to be refreshAssetList ?) is compatible with what the library does with the callback (the arguments it passes to it and what it does with the return value).

If it returns a promise instead, that would look something like this:

function deleteIFAsset(a) {
    var id1 = a.id;
    IframeCloudEditor.deleteFileFromTimeline(id1).then(refreshAsseListt);
}

("Promises" are also sometimes called "futures" or "deferred objects.")

if you can change the code of deleteFileFromTimeLine, you can change it to return the result of the confirmation. and execute refreshAsseListt. example

function deleteFileFromTimeLine(ID)
{
...
return Confirm('Delete File?');
}

and change your code like this

function deleteIFAsset(a) {
    var id1 = a.id;
    if(IframeCloudEditor.deleteFileFromTimeline(id1))
{
    refreshAsseListt();
}
}

You are searching for a solution, to execute your javascript synchronous. But javascript is always executed synchronously except for special cases like ajax requests or file access.

My advice is to use a callback function to solve this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM